package com.bwie.conferenceroom.initialize;

import com.alibaba.fastjson.JSONObject;
import com.bwie.common.domain.request.ConferenceRoomReq;
import com.bwie.common.domain.response.ConferenceRoomRes;
import com.bwie.conferenceroom.service.ConferenceRoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
public class ConferenceRoomInitialize implements ApplicationRunner {
    @Autowired
    private ConferenceRoomService conferenceRoomService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 将会议记录初始化到redis中
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        //判断redis中是否已存入会议室记录
        String conferenceRoomListStr = redisTemplate.opsForValue().get("ConferenceRoomResList");
        List<ConferenceRoomRes> list = JSONObject.parseArray(conferenceRoomListStr, ConferenceRoomRes.class);
        //redis中没有就查询数据库
        if (CollectionUtils.isEmpty(list)){
            ConferenceRoomReq conferenceRoomReq = new ConferenceRoomReq();
            //数据库中有记录则存入redis
            List<ConferenceRoomRes> conferenceRoomList = conferenceRoomService.getConferenceRoomList(conferenceRoomReq);
            if (!CollectionUtils.isEmpty(conferenceRoomList)){
                redisTemplate.opsForValue().set("ConferenceRoomResList",JSONObject.toJSONString(conferenceRoomList));
            }
        }
    }
}
